package user

import (
	"encoding/json"

	"gitee.com/xgotool/backend-framework-template/model"
	"gitee.com/xgotool/backend-framework-template/service/users"
	"gitee.com/xiaoyutab/xgotool/individual/xginplus"
)

// 创建用户操作
//
//	POST	/user/create
func Create(c *xginplus.Context) *xginplus.Response {
	mod := model.User{}
	err := c.Bind(&mod)
	if err != nil {
		return c.Error(err)
	}
	if mod.UserName == "" {
		return c.Errorf("用户名不能为空")
	}
	if mod.Id == 0 && mod.Password == "" {
		return c.Errorf("密码不能为空")
	}
	if mod.Id == 0 {
		if err := users.CheckUserName(mod.UserName, mod.Id); err != nil {
			return c.Error(err)
		}
	} else {
		old, err := users.Info(mod.Id, true)
		if err != nil {
			return c.Error(err)
		}
		mod.Avatar = old.Avatar       // 头像禁止在此处进行修改
		mod.LastLogin = old.LastLogin // 最后登录时间禁止修改
		if mod.UserName != old.UserName {
			return c.Errorf("登录用户名禁止修改")
		}
	}
	b, _ := json.Marshal(mod.RoleIds)
	mod.RoleList = string(b)
	err = users.Create(&mod)
	if err != nil {
		return c.Error(err)
	}
	return c.SuccessEmpty()
}
